<template>
  <div
    class="ebooks"
    id="ebooks"
  >
    <!-- <button @click="prePage" style="position: absolute;z-index: 100000; left: 0;top: 0;">上一页</button>
    <button @click="nextPage" style="position: absolute;z-index: 100000; right: 0;top: 0;">下一页</button> -->
    <watermark
      v-if="showEbookWatermark"
      :watermarkContent="ebookWatemarkConfig && ebookWatemarkConfig.contentType == 2 ? ebookWatemarkConfig.content : ''"
      :fontSize="ebookWatemarkConfig && ebookWatemarkConfig.size ? ebookWatemarkConfig.size : 14"
      :contentFillStyle="ebookWatemarkConfig && ebookWatemarkConfig.color ? ebookWatemarkConfig.color : '#999999'"
      :opacityNum="ebookWatemarkConfig ? ebookWatemarkConfig.transparent / 100 : 0.3"
      :addStyle="'z-index: 102'"
    ></watermark>
    <ebooks-title :ifMenuShow="false"></ebooks-title>

    <div
      class="read-wrapper"
      id="readWrapper"
      style="transform: translateY(-2.2rem);"
      :class="{'c-bg-f2':ebookDetail && ebookDetail.formatType == 2}"
      ref="readWrapper"
    >
      <div class="page-turn-anim3" id="J_page-turn-anim3"></div>
      <ebooks-book-mark
        :offsetY="offsetY"
        :isBookMark="isBookMark"
        @setIsBookmark="setIsBookmark"
      ></ebooks-book-mark>
      <!-- epub电子书 -->
      <template v-if="ebookDetail && ebookDetail.formatType == 2">
        <div class="read-book-container">
          <div id="J_read-clone" class="read-clone" :style="{background: themeBackground}">
            <div id="J_epub-view-clone" class="epub-view-clone"></div>
          </div>
          <div
            id="read"
            class="read"
            :style="{background: themeBackground}"
          ></div>
        </div>

      </template>
      <template v-else-if="ebookDetail && ebookDetail.formatType == 1">
        <div
          class="pdfBook"
          id="pdfBook"
        >
          <div
            class="pdfBook-content closeBig"
            @touchstart="touchstart"
            @touchmove="move"
            @touchend="moveEnd"
            @mousedown="touchstart"
            @mousemove="move"
            @mouseup="mouseup"
          >
            <img
              :src="$addXossFilter(pdfUrl)"
              alt=""
              class="pdfImg"
              id="pdfImg"
            >
          </div>
          <div class="c-pa c-p-b16 c-w100 c-fs24 c-ph20 c-textAlign-r c-fc-sblack c-mb12">{{pdfTo}}/{{totalPageNum}}</div>
        </div>
      </template>
      <!-- pdf电子书 -->
      <!-- 引导页 -->
      <div
        class="read-guidePage"
        v-show="readGuidePage"
        @click="handleClickReadGuidePage"
      >
        <div
          class="read-guidePage-left"
          v-show="readLeft"
        >
          <div class="read-guidePage-con">
            <img
              :src="require('@/assets/guidePage-left.png')"
              alt=""
            >
            <p>点击左侧</p>
            <p>上一页</p>
          </div>
        </div>
        <div
          class="read-guidePage-center"
          v-show="readCenter"
        >
          <div class="read-guidePage-con">
            <img
              :src="require('@/assets/guidePage-center.png')"
              alt=""
            >
            <p>点击中间</p>
            <p>打开阅读设置</p>
          </div>
        </div>
        <div
          class="read-guidePage-right"
          v-show="readRight"
        >
          <div class="read-guidePage-con">
            <img
              :src="require('@/assets/guidePage-right.png')"
              alt=""
            >
            <p>点击右侧</p>
            <p>下一页</p>
          </div>
        </div>
      </div>
      <div
        class="read-guidePage-mark"
        v-show="readMark"
        @click="handleClickReadMark"
      >
        <div class="read-guidePage-markCon">
          <img
            src="https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/readmark.png"
            alt=""
          >
          <p>下拉页面可以加书签哦~</p>
        </div>
      </div>
    </div>
    <div
      class="ebook-bookmark-icon-wrapper"
      v-show="isBookMark"
      :style="isBookMark ? fixedStyle : {}"
    >
      <bookmark
        :color="color"
        :width="16"
        :height="60"
      ></bookmark>
    </div>
    <menu-bar
      :ifMenuShow="ifMenuShow"
      :ifTextShow="ifTextShow"
      :ifFontSizeShow="ifFontSizeShow"
      :ifShowContent="ifShowContent"
      :ifThemeShow="ifThemeShow"
      :progress="progress"
      :section="section"
      :sectionName="sectionName"
      :bookAvailable="bookAvailable"
      :formatType="formatType"
      :isBookMark="isBookMark"
      :isShowComment="isShowComment"
      @onProgressChange="onProgressChange"
      @onProgressInput="onProgressInput"
      @prevSection="prevSection"
      @nextSection="nextSection"
      @handleClickShowContent="handleClickShowContent"
      @handleClickAddBook="handleClickAddBook"
      @handleClickTheme="handleClickTheme"
      @handleClickSize="handleClickSize"
      @handleClickComment="handleClickComment"
      @handleClickReadSet="handleClickReadSet"
    ></menu-bar>
    <!-- <ebooks-theme
      :themeList="themeList"
      :ifThemeShow="ifThemeShow"
      :defaultTheme="defaultTheme"
      @setTheme="setTheme"
    ></ebooks-theme> -->
    <!-- <ebooks-font-size ref="ebooksFontSize" :fontSizeList="fontSizeList" :ifFontSizeShow="ifFontSizeShow" :defaultFontSize="defaultFontSize" @setFontSize="setFontSize"></ebooks-font-size> -->
    <ebooks-content
      ref="ebooksContent"
      :ifShowContent="ifShowContent"
      :navigation="navigation"
      :bookAvailable="bookAvailable"
      :bookmark="bookmark"
      :pdfcatalog="pdfcatalog"
      :pdfmark="pdfmark"
      :markingArray="markingArray"
      :formatType="formatType"
      :dataStatus="dataStatus"
      :hasPermission="hasPermission"
      :watchPermission="watchPermission"
      @handleClickPdfJumpTo="handleClickPdfJumpTo"
      @handleClickDelete="handleClickDelete"
      @jumpTo="jumpTo"
      @pdfJumpTo="pdfJumpTo"
      @displaySearch="displaySearch"
      @handleClickBookMark="handleClickBookMark"
      @scrollContent="scrollContent"
      @handleClickHightLine="handleClickHightLine"
    >
    </ebooks-content>
    <transition name="fade">
      <div
        class="content-mask"
        v-show="ifShowContent"
        @click="hideContent"
      >
      </div>
    </transition>
    <!-- 阅读设置 -->
    <ebooks-read-set :isShow.sync="isShowReadSet" :defaultTheme="defaultTheme" :pageTurnType="pageTurnType" :defaultFontSize="defaultFontSize" :themeList="themeList" @setTheme="setTheme" @setFontSize="setFontSize" @setPageTurnType="setPageTurnType"></ebooks-read-set>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { utilJs } from "@/utils/common.js";
// import { EbooksCreateEvent, previewImgEvent } from "@/components/homePage/ebooks/ebooks.js";
import { decrypt } from "@/utils/aesTool.js";
import PinchZoom from 'pinch-zoom-js';
import MenuBar from '@/components/homePage/ebooks/menuBar.vue';
import EbooksTitle from '@/components/homePage/ebooks/ebooksTitle.vue';
import EbooksContent from '@/components/homePage/ebooks/ebooksContent.vue';
import EbooksBookMark from '@/components/homePage/ebooks/ebooksBookMark.vue';
// import EbooksTheme from '@/components/homePage/ebooks/ebooksTheme.vue';
// import EbooksFontSize from '@/components/homePage/ebooks/ebooksFontSize.vue';
import Bookmark from '@/components/homePage/ebooks/bookmark.vue';
import Watermark from "@/components/templates/common/watermark.vue";
import EbooksReadSet from "@/components/templates/ebooks/ebooksReadSet.vue";
import { getBindPhoneSetting } from "@/utils/checkUnBindPhone.js";
// import EasyMarker from 'easy-marker';
// import Epub from 'epubjs';
const WHITE = '#fff';
const BLUE = '#248AFD';
let ePub = null;
let DOWNLLOAD_URL = '';
const LIMIT = 1;
let page = 1;
let pageIndex = 1;
let contentIndex = 1;
const CONTENTLIMIT = 20;
let recordTimeTmp = null;
let easyMarker = null;
let EasyMarker = null;
export default {
  name: 'Ebook',
  components: {
    MenuBar,
    EbooksContent,
    EbooksTitle,
    EbooksBookMark,
    Bookmark,
    // EbooksTheme,
    // EbooksFontSize,
    Watermark,
    EbooksReadSet
  },
  data() {
    return {
      ifMenuShow: false,
      ifTextShow: false,
      // 图书是否处于可用状态
      bookAvailable: true,
      section: '', //页码
      progress: 0, //进度
      sectionName: '', //章节名称
      ifShowContent: false,
      navigation: {},
      bookmark: [], //书签数组
      ebId: '', //电子书id
      ebrId: '', //电子书资源id
      inputPwd: '', //电子书密码
      ebookDetail: null, //电子书阅读器数据
      readingRecord: null, //阅读记录
      baseInfo: null,
      content: null,
      pdfArray: [], //pdf数据
      pdfIndex: 0,
      pdfUrl: '', //pdf图片地址
      defaultPdfArray: [], //默认pdf数组
      totalPageNum: 0, //总数
      pdfcatalog: [], //pdf目录
      pdfmark: [], //pdf书签
      formatType: 0, //类型
      dataStatus: 'HAS_MORE_DATA',
      canscroll: true,
      trailChaptersNum: 0, //试读章节数
      watchPermission: 0, //是否开启试读
      readGuidePage: 1, //引导页显示,0不显示1显示
      hasPermission: false,
      cfi: '', //存储得进度内容
      isWechatIos: false,
      offsetY: 0,
      isBookMark: false,
      readMark: false,
      epiId: '',
      readLeft: false,
      readCenter: false,
      readRight: true,
      pdfTo: 0, //pdf的当前页数
      touchSlide: {
        startX: 0,
        startY: 0,
        endX: 0,
        endY: 0,
        direction: -1
      },
      markIdArray: [],
      accessToken: '',
      markingArray: [], //划线数据
      isTouchMove: false,
      beginX: '',
      beginY: '',
      endX: '',
      endY: '',
      swipeLeft: false,
      swipeRight: false,
      bindPhoneSetting: null,
      themeList: [
        {
          name: 'bluse',
          style: {
            body: {
              'color': '#46738D!important',
              'background': 'linear-gradient(225deg, #E4F2F8 0%, #B8D6E6 100%)',
            },
            pageTurn:{
              'background':'linear-gradient(90deg, #E4F2F8 0%, #B8D6E6 100%)'
            }
          }
        },
        {
          name: 'Pink',
          style: {
            body: {
              'color': '#9E526A!important',
              'background': 'linear-gradient(225deg, #FCE0DD 0%, #FDB7AF 100%)'
            },
            pageTurn:{
              'background': 'linear-gradient(90deg, #FCE0DD 0%, #FDB7AF 100%)'
            }
          }
        },
        {
          name: 'Brown',
          style: {
            body: {
              'color': '#725335!important',
              'background': 'linear-gradient(225deg, #FFDFBF 0%, #E6B589 100%)'
            },
            pageTurn:{
              'background': 'linear-gradient(90deg, #FFDFBF 0%, #E6B589 100%)'
            }
          }
        },
        {
          name: 'Dark',
          style: {
            body: {
              'color': '#D6DDE8!important',
              'background': 'linear-gradient(225deg, #235A86 0%, #041B4C 100%)',
            },
            pageTurn:{
              'background': 'linear-gradient(90deg, #235A86 0%, #041B4C 100%)',
            }
          }
        },
        {
          name: 'Default',
          style: {
            body: {
              'color': '#000!important',
              'background': '#F2F2F2'
            },
            pageTurn:{
              'background': '#F2F2F2'
            }
          }
        },
        {
          name: 'Gold',
          style: {
            body: {
              'color': '#000!important',
              'background': '#DFDCCC'
            },
            pageTurn:{
              'background': '#DFDCCC'
            }
          }
        },
        {
          name: 'Eye',
          style: {
            body: {
              'color': '#000!important',
              'background': '#BADBBD'
            },
            pageTurn:{
              'background': '#BADBBD'
            }
          }
        },
        {
          name: 'Night',
          style: {
            body: {
              'color': '#fff!important',
              'background': '#000'
            },
            pageTurn:{
              'background': '#000'
            }
          }
        }
      ],
      ifThemeShow: false,
      fontSizeList: [
        { fontSize: 12 },
        { fontSize: 14 },
        { fontSize: 16 },
        { fontSize: 18 },
        { fontSize: 20 },
        { fontSize: 22 },
        { fontSize: 24 }
      ],
      defaultFontSize: localStorage.getItem('defaultFontSize') || 16,
      // ifFontSizeShow: false,
      defaultTheme: localStorage.getItem('defaultTheme') || 0,
      isTouchFlage: false, //判断当前为点击还是滑动
      themeBackground: '#F2F2F2',
      pageTurnBackground:"#F2F2F2",
      touchStartTime: '',
      cfg: JSON.parse(localStorage.getItem("cfg")),
      isShowComment: false,
      // 训练营参数
      ttId: '',
      tpId: '',
      tlId: '',
      showEbookWatermark: false,
      ebookWatemarkConfig: JSON.parse(localStorage.getItem("ebookWatemarkConfig")) || '',
      isShowReadSet: false, // 是否显示阅读设置
      pageTurnType: 1, //电子书翻页方式
    }
  },
  watch: {
    isBookMark(isBookMark) {
      if (isBookMark) {
        this.color = BLUE;
      } else {
        this.color = WHITE;
      }
    },
  },
  computed: {
    ...mapState({
      eBooksSrc: state => state.oem_store.eBooksSrc
    }),
    fixedStyle() {
      return {
        position: 'fixed',
        right: 0,
        top: 0
      }
    }
  },
  created() {
    utilJs.appShare(this);
  },
  deactivated() {
    this.$cjConfirm.hide();
    this.$loading.hide();
    clearTimeout(recordTimeTmp)
    recordTimeTmp = null;
    if (this.book) {
      this.book.destroy();
    }
  },
  methods: {
    cloneIframe() {
      if (!this._pageTurnAniming) {
        const iframe = document.querySelector('#read iframe');
        const cloneContainer = document.querySelector('#J_epub-view-clone');
        if (!iframe) return;
        const manager = this.rendition.manager;
        const viewElem = manager.views && manager.views.container;
        console.log(viewElem.scrollWidth, manager.scrollLeft);
        const clonedIframe = iframe.cloneNode(true);

        cloneContainer.innerHTML = ''; // 清空之前的克隆内容
        cloneContainer.appendChild(clonedIframe);
        cloneContainer.style.width = `${viewElem.scrollWidth}px`;
        // 如果需要拷贝内容
        const originalDoc = iframe.contentDocument || iframe.contentWindow.document;
        const clonedDoc = clonedIframe.contentDocument || clonedIframe.contentWindow.document;
        clonedDoc.open();
        clonedDoc.write(originalDoc.documentElement.outerHTML);
        clonedDoc.close();
        let style = this.getStyle("cloneReset");
        let head = clonedIframe.contentDocument.documentElement.getElementsByTagName('head')[0];
        if (head) head.appendChild(style);
        if (clonedDoc.querySelector("body")) {
          clonedDoc.querySelector("body").style.background = window.getComputedStyle(originalDoc.querySelector("body")).backgroundImage;
         }
        if (typeof manager.scrollLeft != 'undefined') {
          cloneContainer.style.left = `-${manager.scrollLeft}px`;
        } else {
          cloneContainer.style.left = `0px`;
        }
      } else {
        clearTimeout(this.cloneIframeTimer);
        this.cloneIframeTimer = setTimeout(() => {
          this.cloneIframe();
        }, this._animTime)
      }
    },
    setProgressRatio(progress, first) {
      let data = {
        ttId: this.ttId, //营期ID
        tpId: this.tpId, //环节ID
        tlId: this.tlId, //课时ID
        ratio: progress >= 90 ? 100 : progress, //完成进度0-100
        duration: 0,
        ebrId: this.ebrId,
        first: first
      };
      if (this.ttId && this.tpId && this.tlId) {
        utilJs.postMethod(
          global.apiurl + "k12/trainings/progress",
          data,
          function (res) { }
        );
      }
    },
    handleClickReadGuidePage() {
      if (this.readRight) {
        this.readRight = false;
        this.readLeft = true;
        return;
      }
      if (this.readLeft) {
        this.readLeft = false;
        this.readCenter = true;
        return;
      }
      if (this.readCenter) {
        this.readCenter = false;
        this.readGuidePage = false;
        this.readMark = true;
        return;
      }
    },
    setIsBookmark(setIsBookmark, text, offsetY) {
      this.isBookMark = setIsBookmark;
      if (setIsBookmark && text == '松手添加书签' && offsetY == 0) {
        //true 添加书签
        this.handleClickAddBook(setIsBookmark);
        this.color = BLUE;
      } else if (!setIsBookmark && text == '松手删除书签' && offsetY == 0) {
        this.moveBookmark();
        this.color = WHITE;
      }
      this.firstOffsetY = null;
      setTimeout(() => {
        this.offsetY = 0;
        // this.$refs.readWrapper.style.transition = ''
      }, 200)
    },
    touchstart(e) {
      e.preventDefault();
      e.stopPropagation();
      this.isTouchFlage = false;
      this.touchStartTime = e.timeStamp;
      this.touchSlide.startX = (e.targetTouches && e.targetTouches[0].pageX) || e.clientX;
      this.touchSlide.startY = (e.targetTouches && e.targetTouches[0].pageY) || e.clientY;
    },
    // 翻页start
    pageStart(e) {
      this.beginX = (e.targetTouches && e.targetTouches[0].screenX) || e.pageX;
      this.beginY = (e.targetTouches && e.targetTouches[0].screenY) || e.pageY;
      this.swipeLeft = false;
      this.swipeRight = false;
    },
    // 判断滑动方向
    isPageStart(e) {
      this.endX = e.targetTouches[0].screenX || e.pageX;
      this.endY = e.targetTouches[0].screenY || e.pageY;
      // 判断滑动
      if (Math.abs(this.endX - this.beginX) - Math.abs(this.endY - this.beginY) > 0) {
        // 向右滑动
        if (this.endX - this.beginX > 0) {
          console.log('---------我向右滑动了-------')
          this.swipeRight = true;
          this.swipeLeft = false;
        } else {
          // 向左滑动
          console.log('---------我向左滑动了')
          this.swipeLeft = true;
          this.swipeRight = false;
        }
      }
    },
    // 滚动move
    move(e) {
      e.preventDefault();
      e.stopPropagation();
      let _this = this;
      this.isTouchFlage = true;
      this.touchSlide.endX = (e.targetTouches && e.targetTouches[0].pageX) || e.clientX;
      this.touchSlide.endY = (e.targetTouches && e.targetTouches[0].pageY) || e.clientY;
      // 判断向下滑动
      if (Math.abs(this.touchSlide.endY - this.touchSlide.startY) > Math.abs(this.touchSlide.endX - this.touchSlide.startX) && (this.touchSlide.endY - this.touchSlide.startY) > 0) {
        var slide = (this.touchSlide.startY - this.touchSlide.endY) / 100;
        this.touchSlide.direction == -1 && this.setDirection();
        this.touchSlide.direction === 3 && requestAnimationFrame(function () {
          document.getElementById("readWrapper").style.transform = "translateY(" + Math.min(-1 - slide, 0) + "rem)";
        })
        if (this.touchSlide.direction == 3) {
          this.isTouchFlage = false;
          window.requestAnimationFrame(function () {
          })
        } else {
          this.setDirection();
        }
        if (_this.firstOffsetY) {
          _this.offsetY = (e.targetTouches && e.changedTouches[0].clientY || e.clientY) - _this.firstOffsetY;
        } else {
          _this.firstOffsetY = (e.targetTouches && e.changedTouches[0].clientY || e.clientY)
        }
      }

    },
    mouseup(e) {
      let _this = this;
      var timer = null;
      clearTimeout(timer);
      timer = setTimeout(() => {
        const clientWidth = window.innerWidth;
        const offsetx = (e.targetTouches && e.changedTouches[0].pageX) || e.pageX;
        const r = offsetx % clientWidth;
        if (r > clientWidth / 3 * 2) {
          if (_this.isTouchMove) return;
          this.nextPage();
        } else if (r < clientWidth / 3) {
          if (_this.isTouchMove) return;
          this.prePage();
        } else {
          if (_this.touchSlide.direction === 3) return;
          if (_this.isTouchMove) return;
          this.toggleMenu();
        }
      }, 450)
      this.touchSlideHandle();
      this.touchSlide = {
        startX: 0,
        startY: 0,
        endX: 0,
        endY: 0,
        direction: -1
      }
      if (this.offsetY > 0) {
        this.firstOffsetY = null;
        setTimeout(() => {
          this.offsetY = 0;
        }, 200)
      }
    },
    moveEnd(e) {
      let _this = this;
      // let X = this.touchSlide.endX - this.touchSlide.startX;
      // let Y = this.touchSlide.endY - this.touchSlide.startY;
      const time = e.timeStamp - this.touchStartTime;
      const offsetX = e.changedTouches[0].clientX - this.touchSlide.startX;
      // 判断滑动方向
      if (offsetX > 60 && time < 500) {
        // 向右
        if (_this.isTouchMove) return;
        this.prePage();
        console.log('-----向右发生滑动了-----', offsetX, time)
      } else if (offsetX < -60 && time < 500) {
        // 向左
        if (_this.isTouchMove) return;
        this.nextPage();
        console.log('-----向左发生滑动了-----', offsetX, time)
      } else {
        // 单击
        if ((e.touches && e.touches.length < 2) && this.touchSlide.direction != 3) {
          const clientWidth = window.innerWidth;
          const offsetx = (e.targetTouches && e.changedTouches[0].pageX) || e.pageX;
          const r = offsetx % clientWidth;
          if (r > clientWidth / 3 * 2) {
            if (_this.isTouchMove) return;
            this.nextPage();
          } else if (r < clientWidth / 3) {
            if (_this.isTouchMove) return;
            this.prePage();
          } else {
            if (_this.touchSlide.direction === 3) return;
            if (_this.isTouchMove) return;
            this.toggleMenu();
          }
        }
      }
      this.touchSlideHandle();
      this.touchSlide = {
        startX: 0,
        startY: 0,
        endX: 0,
        endY: 0,
        direction: -1
      }
      if (this.offsetY > 0) {
        this.firstOffsetY = null;
        setTimeout(() => {
          this.offsetY = 0;
        }, 200)
      }
    },
    //分享
    wechatShare: function () {
      let title = this.ebookDetail.name;
      let shareImg = this.ebookDetail.avatar;
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/ebooks/ebooksDetail?id=${this.ebId}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = this.ebookDetail.desc || window.localStorage.getItem("shareDesc");
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc);
    },
    //手机端分享
    appShare: function () {
      let title = this.ebookDetail.name;
      let shareImg = this.ebookDetail.avatar;
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/ebooks/ebooksDetail?id=${this.ebId}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = this.ebookDetail.desc || window.localStorage.getItem("shareDesc");
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    },
    // 关闭引导页
    handleClickReadMark() {
      this.readMark = false;
    },
    scrollContent(event) {
      if (this.canscroll) {
        // 判断是否触发
        let scroll = event.target.scrollTop;
        let scrollListH = document.getElementById("scrollList").clientHeight;
        let scrollContentH = event.target.clientHeight;
        let loadingH = document.getElementById("loading").clientHeight;
        if (scrollListH - (scroll + scrollContentH + loadingH) >= 0) {
          this.canscroll = false; //锁定滚动触发条件
          this.getIndexByPage();
        }
      }
    },
    // 保存阅读记录
    saveReadingRecord(ebrrId, page, cfi, first, href, progress) {
      if (recordTimeTmp) {
        clearTimeout(recordTimeTmp)
      }
      recordTimeTmp = setTimeout(() => {
        clearTimeout(recordTimeTmp)
        recordTimeTmp = null;
        this.saveReadingRecordServer(ebrrId, page, cfi, first, href, progress)
      }, 100);
    },
    saveReadingRecordServer(ebrrId, page, cfi, first, href, progress) {
      utilJs.postMethod(`${global.apiurl}ebooks/saveReadingRecord`, { ebId: this.ebId, ebrId: this.ebrId, ebrrId: ebrrId, page: page, cfi: cfi, totalPageNum: this.totalPageNum, first: first, accessToken: this.accessToken, href: href, progress: progress }, res => {
        if (this.formatType == 2) {
          this.cfi = res.cfi;
          localStorage.setItem("locations", res.cfi);//存储当前进度条
          // if (this.cfiObject && this.cfiObject.cfi) {
          //   // 渲染存储得值
          //   this.book.rendition.display(this.cfiObject.cfi);
          // } else {
          //   this.display();
          // }
        }
        this.setProgressRatio(progress, first);
      }, failRes => {
        this.$routerGo(this, "replace", {
          path: "/error/emptyPage",
          query: {
            from: "",
            info: "电子书已下架，请联系管理员！"
          }
        });
      })
    },
    // 添加/删除书签
    optBookmark(opt, page, content, ebbkId, href) {
      utilJs.postMethod(`${global.apiurl}ebooks/optBookmark/${this.ebId}`, { opt: opt, page: page, formatType: this.formatType, content: content, ebbkId: ebbkId, accessToken: this.accessToken, href: href }, res => {
        if (this.formatType == 2 && opt == 1) {
          if (this.bookmark.length == 0) {
            this.bookmark.push({
              cfi: content.cfi,
              text: content.text,
              title: content.title,
              time: content.time,
              ebbkId: res
            })
            this.$showCjToast({
              text: "成功添加书签",
              type: "success",
            });
            this.isBookMark = true;
          } else if (this.bookmark.length > 0) {
            let isInsertEpub = this.bookmark.some(item => {
              if (item.cfi == content.cfi) {
                return true;
              }
            })
            if (isInsertEpub) {
              this.isBookMark = false;
              this.$cjConfirm({
                title: '', //
                titleCenter: true, //标题是否居中
                message: '已存在当前书签,无需添加',
                messageCenter: true, //内容是否居中
                showMasker: true, //是否显示透明背景
                clickCloseModal: false, //是否点击透明背景关闭弹窗
                showCancelButton: false, //是否显示取消按钮
                cancelButtonText: '', //取消按钮文本
                confirmButtonText: '', //确认按钮文本
              })
            } else {
              this.bookmark.push({
                cfi: content.cfi,
                text: content.text,
                title: content.title,
                time: content.time,
                ebbkId: res
              })
              this.$showCjToast({
                text: "成功添加书签",
                type: "success",
              });
              this.isBookMark = true;
            }
          }
        }
      }, failRes => {
        this.$routerGo(this, "replace", {
          path: "/error/emptyPage",
          query: {
            from: "",
            info: "电子书已下架，请联系管理员！"
          }
        });
      })
    },
    // 获取电子书书签列表
    getBookmarkList() {
      let _this = this;
      return new Promise(function (resolve, reject) {
        utilJs.getMethod(`${global.apiurl}ebooks/getBookmarkList/${_this.ebId}`,
          res => {
            resolve(res);
          },
          failRes => {
            reject(failRes)
            this.$routerGo(this, "replace", {
              path: "/error/emptyPage",
              query: {
                from: "",
                info: "电子书已下架，请联系管理员！"
              }
            });
          }
        )
      })
    },
    // 分页获取电子书目录
    getIndexByPage() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.dataStatus = 'LOADING';
      utilJs.getMethod(`${global.apiurl}ebooks/getIndexByPage/${this.ebId}?index=${pageIndex}&ttId=${this.ttId}&page=${contentIndex}&limit=${CONTENTLIMIT}&accessToken=${this.accessToken}`,
        res => {
          this.trailChaptersNum = res.trailChaptersNum; //试读章节数
          this.watchPermission = res.watchPermission; //开启章节数 0未开启试读1开启试读
          if (res.formatType == 1) {
            if (pageIndex == 1) {
              this.pdfcatalog = res.list.data;
            } else {
              this.pdfcatalog = [...this.pdfcatalog, ...res.list.data]
            }
            if (res.list.total * 1 == this.pdfcatalog.length) {
              this.dataStatus = res.list.total * 1 == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
              if (this.dataStatus == 'NO_MORE_DATA') {
                this.canscroll = false;
              }
            } else {
              this.dataStatus = 'HAS_MORE_DATA';
              pageIndex += CONTENTLIMIT;
              contentIndex++;
              this.canscroll = true;
            }
            this.bookAvailable = false;
          } else {
            // this.navigation = res.list;
            // this.dataStatus = 'NO_MORE_DATA';
            if (pageIndex == 1) {
              this.navigation = res.list.data;
            } else {
              this.navigation = [...this.navigation, ...res.list.data]
            }
            if (res.list.total * 1 == this.navigation.length) {
              this.dataStatus = res.list.total * 1 == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
              if (this.dataStatus == 'NO_MORE_DATA') {
                this.canscroll = false;
              }
            } else {
              this.dataStatus = 'HAS_MORE_DATA';
              pageIndex += CONTENTLIMIT;
              contentIndex++;
              this.canscroll = true;
            }
          }
        },
        failRes => {
          this.dataStatus = 'DATA_ERROR';
          // this.$routerGo(this, "replace", {
          //   path: "/error/emptyPage",
          //   query: {
          //     from: "",
          //     info: "电子书已下架，请联系管理员！"
          //   }
          // });
        }
      )
    },
    // 分页获取电子书内容
    getEbookContentByPage() {
      utilJs.getMethod(`${global.apiurl}ebooks/getEbookContentByPage/${this.ebId}?page=${page}&limit=${LIMIT}&accessToken=${this.accessToken}`,
        res => {
          //没权限进来直播返回详情页
          if (res.baseInfo.assetStatus == -1) {
            this.$showCjToast({
              text: "该电子书已被管理员删除，如有疑问请咨询客服",
              type: "warn",
            });
            this.$routerGo(this, "replace", {
              path: `/homePage/ebooks/ebooksDetail?id=${this.ebId}`
            })
            return;
          }
          this.baseInfo = res.baseInfo;
          this.defaultPdfArray = res.content.data;
          this.pdfUrl = res.content.data[0].url;
          this.totalPageNum = res.baseInfo.totalPageNum;
          this.epiId = res.content.data[0].epiId;
          this.pdfTo = res.content.to;
          this.ifTextShow = false;
          this.setProgress(Math.floor((res.content.current_page / res.baseInfo.totalPageNum) * 100));//设置progress，等于设置了进度条进度
          if (page == 1) {
            this.pdfArray = res.content.data;
          } else {
            this.pdfArray = [...this.pdfArray, ...res.content.data]
          }
          if (this.pdfmark.length > 0) {
            if (this.pdfmark.some(item => item.page === page)) {
              this.isBookMark = true;
            } else {
              this.isBookMark = false
            }
          } else {
            this.isBookMark = false
          }
          this.saveReadingRecord(0, page, '', 0, '', this.progress);
          // this.setProgressRatio(this.progress, 0);
        },
        failRes => {
          // this.$routerGo(this, "replace", {
          //   path: "/error/emptyPage",
          //   query: {
          //     from: "",
          //     info: "电子书已下架，请联系管理员！"
          //   }
          // });
        }
      )
    },
    // 加载电子书阅读器数据
    getEbookViwer() {
      let _this = this;
      utilJs.getMethod(`${global.apiurl}ebooks/getEbookViewer/${this.ebId}?page=${page}&encrypt=${this.inputPwd}&ttId=${this.ttId}&accessToken=${this.accessToken}`,
        res => {
          //没权限进来直播返回详情页
          if (res.assetStatus == -1) {
            this.$showCjToast({
              text: "该电子书已被管理员删除，如有疑问请咨询客服",
              type: "warn",
            });
            this.$routerGo(this, "replace", {
              path: `/homePage/ebooks/ebooksDetail?id=${this.ebId}`
            })
            return;
          }
          //没权限进来直播返回详情页
          if (!res.hasPermission && res.watchPermission != 1) {
            this.$showCjToast({
              text: "抱歉，您还未获得阅读该电子书的权限！",
              type: "warn",
            });
            this.$routerGo(this, "replace", {
              path: `/homePage/ebooks/ebooksDetail?id=${this.ebId}`
            })
            return;
          }
          // 获取电子书阅读器数据，再去请求相应得接口内容
          if (res.resource) {
            res.resource = decrypt(res.resource)
          }
          // 是否开启评论功能
          if (this.cfg && this.cfg.enableComment == 1 && this.cfg.enableEbookComment == 1) {
            this.isShowComment = true;
          }
          this.ebookDetail = res.ebookDetail;
          this.readingRecord = res.readingRecord;
          this.formatType = res.ebookDetail.formatType;
          this.trailChaptersNum = res.trailChaptersNum;
          this.hasPermission = res.hasPermission;
          this.totalPageNum = res.ebookDetail.totalPageNum;
          // this.count = res.count;
          page = res.readingRecord.page;
          this.getBookmarkList().then(res => {
            if (res.formatType == 1) {
              this.pdfmark = res.list;
            } else {
              this.bookmark = res.list;
            }
            if (res.list.length > 0) {
              if (res.list.some(item => item.page === page)) {
                this.isBookMark = true;
              } else {
                this.isBookMark = false
              }
            } else {
              this.isBookMark = false
            }
          })
          // this.setProgress(res.readingRecord.progress);
          // 根据请求回来得page，请求分页获取电子书内容
          if (res.ebookDetail.formatType == 1) {
            this.getEbookContentByPage();
          } else {
            DOWNLLOAD_URL = res.resource;
            this.showEpub();
            this.markingRestory();
          }
          this.wechatShare();
          setDocumentTitle(res.ebookDetail.name);
          if (res.ebookDetail.formatType == 1) {
            this.$nextTick(() => {
              let el = document.querySelector('.pdfImg')
              new PinchZoom(el, {
                draggableUnzoomed: false,
                onDragStart: function () {
                  console.log('-----onDragStart-----')
                },
                onDragEnd: function () {
                  console.log('-----onDragEnd-----')
                },
                onZoomStart: function (object, event) {
                  console.log('------onZoomStart-----')
                },
                onZoomEnd: function (object, event) {
                  if (object.zoomFactor == 1) {
                    _this.isTouchMove = false;
                  } else if (object.zoomFactor > 1) {
                    _this.isTouchMove = true;
                  }
                  console.log('--------onZoomEnd-----')
                },
                onZoomUpdate: function (object, event) {
                  if (object.zoomFactor == 1) {
                    _this.isTouchMove = false;
                  } else if (object.zoomFactor > 1) {
                    _this.isTouchMove = true;
                  }
                  console.log('------onZoomUpdate-----', object)
                },
                onDragUpdate: function (object, event) {
                  console.log('-------onDragUpdate----', object)
                  if (object.zoomFactor == 1) {
                    _this.isTouchMove = false;
                  } else if (object.zoomFactor > 1) {
                    _this.isTouchMove = true;
                  }
                },
                onDoubleTap: function (object, event) {
                  _this.isTouchMove = true;
                  console.log('------onDoubleTap------', object)
                }
              })
            })
          }
        },
        failRes => {
          this.$routerGo(this, "replace", {
            path: "/error/emptyPage",
            query: {
              from: "",
              info: "电子书已下架，请联系管理员！"
            }
          });
        }
      )
    },
    // 根据链接跳转到指定书签页
    displaySearch(href) {
      this.display(href, () => {
        this.ifMenuShow = false;
        this.ifShowContent = false;
        // this.ifThemeShow = false;
        // this.ifFontSizeShow = false;
        this.isShowReadSet = false;
        const currentLocation = this.book.rendition.currentLocation();//获取当前的位置
        const startCfi = currentLocation.start.cfi;
        this.saveReadingRecord(0, page, startCfi, 0, currentLocation.start.href, this.progress);
        // this.setProgressRatio(this.progress, 0);
      })
    },
    // 根据链接跳转到指定位置
    jumpTo(href, isLock) {
      if (isLock == 1) {
        // 锁住状态
        this.$showCjToast({
          text: "购买之后解锁章节",
          type: "warn",
        });
        return true;
      } else {
        this.display(href, () => {
          this.ifMenuShow = false;
          this.ifShowContent = false;
          // this.ifThemeShow = false;
          // this.ifFontSizeShow = false;
          this.isShowReadSet = false;
          setTimeout(() => {
            const currentLocation = this.book.rendition.currentLocation();//获取当前的位置
            const startCfi = currentLocation.end.cfi;
            this.saveReadingRecord(0, page, startCfi, 0, currentLocation.start.href, this.progress);
            // this.setProgressRatio(this.progress, 0);
          }, 1000);
        })
      }
    },
    pdfJumpTo(pageNum, isLock) {
      if (isLock == 1) {
        // 锁住状态
        this.$showCjToast({
          text: "购买之后解锁章节",
          type: "warn",
        });
        return true;
      } else {
        page = pageNum;
        this.getEbookContentByPage();
        this.ifMenuShow = false;
        this.ifShowContent = false;
        // this.saveReadingRecord(0, page, '', 0, '', this.progress);
      }
    },
    handleClickPdfJumpTo(pageNum, isEdit) {
      if (isEdit) {
        console.log(111)
      } else {
        page = pageNum;
        this.getEbookContentByPage();
        this.ifMenuShow = false;
        this.ifShowContent = false;
        // this.saveReadingRecord(0, page, '', 0, '', this.progress);
      }
    },
    // 点击中间部分
    toggleMenu() {
      this.ifMenuShow = !this.ifMenuShow;
      this.ifTextShow = false;
      this.isShowReadSet = false;
      // if (this.ifThemeShow) {
      //   this.ifThemeShow = false;
      //   this.ifMenuShow = false;
      // }
      // if (this.ifFontSizeShow) {
      //   this.ifFontSizeShow = false;
      //   this.ifMenuShow = false;
      // }
      // this.ifTextShow = !this.ifTextShow;
    },
    // 隐藏菜单栏
    hideMenu() {
      this.ifMenuShow = false;
      // this.ifTextShow = false;
    },
    // progress 进度条的数值,拖动结束后触发事件
    onProgressChange(progress) {
      if (progress == 1) {
        page = 1;
      }
      if (page <= this.trailChaptersNum) {
        this.setProgress(progress);
      }
      if (this.ebookDetail.formatType == 2) {
        // 显示进度条对应的页面
        this.onProgressInputEpub(progress);
      } else {
        let _this = this;
        page = Math.floor((progress / 100) * this.totalPageNum);
        if (page >= 1) {
          if (!this.hasPermission && this.watchPermission == 1 && (page >= this.trailChaptersNum) && (page < this.totalPageNum)) {
            this.$cjConfirm({
              title: '', //
              titleCenter: true, //标题是否居中
              message: '下一章节内容还未解锁,请购买',
              messageCenter: true, //内容是否居中
              showMasker: true, //是否显示透明背景
              clickCloseModal: false, //是否点击透明背景关闭弹窗
              showCancelButton: true, //是否显示取消按钮
              cancelButtonText: '', //取消按钮文本
              confirmButtonText: '', //确认按钮文本
              onConfirm() {
                _this.clickBuy();
              }, //确认事件回调
              onCancel() {
              }, //取消事件回调
            })
            this.setProgress(Math.floor((this.pdfTo / this.totalPageNum) * 100));
            page = this.pdfTo;
            // this.getEbookContentByPage();
            // this.bookAvailable = false;
            this.ifTextShow = false;
            return true;
          } else {
            if (page == 0) {
              page = 1;
            }
            this.setProgress(progress);
            this.getEbookContentByPage();
            // this.saveReadingRecord(0, page, '', 0, '', this.progress);
          }
        } else if (page == this.totalPageNum) {
          this.$cjConfirm({
            title: '', //
            titleCenter: true, //标题是否居中
            message: '已经到最后一页了',
            messageCenter: true, //内容是否居中
            showMasker: true, //是否显示透明背景
            clickCloseModal: false, //是否点击透明背景关闭弹窗
            showCancelButton: false, //是否显示取消按钮
            cancelButtonText: '', //取消按钮文本
            confirmButtonText: '', //确认按钮文本
          })
          return true;
        } else {
          if (page == 0) {
            page = 1;
          }
          this.setProgress(progress);
          this.getEbookContentByPage();
          // this.saveReadingRecord(0, page, '', 0, '', this.progress);
        }
      }
      this.ifTextShow = false;
    },
    onProgressInput(progress) {
      this.ifTextShow = true;
    },
    onProgressInputEpub(progress) {
      let _this = this;
      let curSection = Math.floor(progress / 100 * this.book.navigation.length);
      if (!this.hasPermission && this.watchPermission == 1 && curSection >= this.trailChaptersNum) {
        this.$cjConfirm({
          title: '', //
          titleCenter: true, //标题是否居中
          message: '章节内容还未解锁,请购买',
          messageCenter: true, //内容是否居中
          showMasker: true, //是否显示透明背景
          clickCloseModal: false, //是否点击透明背景关闭弹窗
          showCancelButton: true, //是否显示取消按钮
          cancelButtonText: '', //取消按钮文本
          confirmButtonText: '', //确认按钮文本
          onConfirm() {
            _this.clickBuy();
          }, //确认事件回调
          onCancel() {
          }, //取消事件回调
        })
        const currentLocation = this.book.rendition.currentLocation();//获取当前的位置
        const startCfi = currentLocation.start.cfi;
        const trailChaptersProgress = _this.locations.percentageFromCfi(startCfi);//获取当前的百分比
        this.ifTextShow = false;
        console.log('---未解锁时当前得进度条---', trailChaptersProgress)
        this.setProgress(Math.floor(trailChaptersProgress * 100));
        return true;
      }
      // this.bookAvailable = false;
      this.setProgress(progress);
      this.displayProgress();
    },
    displayProgress() {
      //解决定位页数
      const percentage = this.progress / 100;
      const cfi = this.book.locations.cfiFromPercentage(percentage);
      const location = percentage > 0 ? cfi : 0
      this.display(location)
      this.refleshLocation()
    },
    touchHook(t, e) {
      switch (t) {
        case 'tap':
          this.tapHandle(e);
          break;
        case 'longtap':
          break;
        case 'touchstart':
          this.touchStartHandle(e);
          break
        case 'touchmove':
          this.touchMoveHandle(e);
          break;
        case 'touchend':
          this.touchEndHandle(e);
          break;
        default:
          return !0;
      }
      return !0
    },
    tapHandle(e) {
      this.isTouchFlage = false;
      e.preventDefault();
      if (this.selectStatus != 'none') {
        return;
      }
      //点击到高亮区域，不触发点击事件
      if (easyMarker.highlight.inRegion(e)) {
        return;
      }
      console.log('---------单击事件----------:', e)
      const clientWidth = window.innerWidth;
      const offsetx = (e.targetTouches && e.changedTouches[0].pageX) || e.pageX;
      const r = offsetx % clientWidth;
      if (r > clientWidth / 3 * 2) {
        this.nextPage();
      } else if (r < clientWidth / 3) {
        this.prePage();
      } else {
        this.toggleMenu();
      }
    },
    touchStartHandle(e) {
      this.isTouchFlage = false;
      this.touchSlide.startX = (e.targetTouches && e.targetTouches[0].pageX) || e.pageX;
      this.touchSlide.startY = (e.targetTouches && e.targetTouches[0].pageY) || e.pageY;
      console.log('-----touchstart------')
      this.pageStart(e);
    },
    touchMoveHandle(e) {
      this.isTouchFlage = true;
      if (this.selectStatus != 'none') {
        return;
      }
      e.stopPropagation();
      e.preventDefault();
      if (e.targetTouches == undefined) {
        return
      }
      this.touchSlide.endX = e.targetTouches[0].pageX || e.pageX;
      this.touchSlide.endY = e.targetTouches[0].pageY || e.pageY;
      // 判断当往下滑动的时候
      if (Math.abs(this.touchSlide.endY - this.touchSlide.startY) > Math.abs(this.touchSlide.endX - this.touchSlide.startX) && (this.touchSlide.endY - this.touchSlide.startY) > 0) {
        var slide = (this.touchSlide.startY - this.touchSlide.endY) / 100;
        this.touchSlide.direction == -1 && this.setDirection();
        this.touchSlide.direction === 3 && requestAnimationFrame(function () {
          document.getElementById("readWrapper").style.transform = "translateY(" + Math.min(-1 - slide, 0) + "rem)";
        })
        if (this.touchSlide.direction == 3) {
          window.requestAnimationFrame(function () {
          })
        } else {
          this.setDirection();
        }
        if (this.firstOffsetY) {
          this.offsetY = e.changedTouches[0].clientY - this.firstOffsetY;
        } else {
          this.firstOffsetY = e.changedTouches[0].clientY
        }
      } else {
        this.isPageStart(e);
      }
    },
    // 判断滑动结束
    isPageEnd(e) {
      if (Math.abs(this.endX - this.beginX) - Math.abs(this.endY - this.beginY) > 0) {
        e.stopPropagation();
        e.preventDefault();
        if (this.swipeRight) {
          this.swipeRight = !this.swipeRight;
          // 向右滑动
          this.prePage();
        }
        if (this.swipeLeft) {
          this.swipeLeft = !this.swipeLeft;
          // 向左滑动
          this.nextPage();
        }
      }
    },
    touchEndHandle(e) {
      if (this.selectStatus != 'none') {
        return;
      }
      this.touchSlideHandle();
      this.touchSlide = {
        startX: 0,
        startY: 0,
        endX: 0,
        endY: 0,
        direction: -1
      }
      console.log('---------拖拽结束----------:', e)
      if (this.offsetY > 0) {
        this.firstOffsetY = null;
        setTimeout(() => {
          this.offsetY = 0;
        }, 200)
      }
      if (this.isTouchFlage) {
        this.isPageEnd(e);
      }
    },
    touchSlideHandle() {
      switch (this.touchSlide.direction) {
        case 0:
        case 1:
        case 2:
          break;
        case 3:
          setTimeout(function () {
            document.getElementById("readWrapper").style.transform = "translateY(-2.2rem)"
          }, 100)
      }
    },
    setDirection() {
      this.touchSlide.endX - this.touchSlide.startX < -10 ? this.touchSlide.direction = 0 : this.touchSlide.endX - this.touchSlide.startX > 10 ? this.touchSlide.direction = 1 : this.touchSlide.endY - this.touchSlide.startY < -10 ? this.touchSlide.direction = 2 : this.touchSlide.endY - this.touchSlide.startY > 10 && (this.touchSlide.direction = 3);
    },
    markingRestory() {
      let _this = this;
      utilJs.getMethod(`${global.apiurl}ebooks/getHighLineNoteById/${this.ebId}?accessToken=${this.accessToken}`,
        res => {
          _this.markingArray = res.noteCfi || [];
        },
        failRes => {
          this.$routerGo(this, "replace", {
            path: "/error/emptyPage",
            query: {
              from: "",
              info: "电子书已下架，请联系管理员！"
            }
          });
        }
      )
    },
    textMarkRestore(href) {
      let _this = this;
      utilJs.getMethod(`${global.apiurl}ebooks/getHighLineNoteById/${this.ebId}?href=${href}&accessToken=${this.accessToken}`,
        res => {
          console.log('-------渲染出来得------', res)
          let i = [];
          if (res.noteCfi && res.noteCfi.length > 0) {
            res.noteCfi.forEach((item, index) => {
              let cficontent = _this.book.rendition.getRange(item.cfi);
              i.push({
                id: item.cfi,
                selection: {
                  anchorNode: cficontent.startContainer,
                  anchorOffset: cficontent.startOffset,
                  focusNode: cficontent.endContainer,
                  focusOffset: cficontent.endOffset
                },
                cfi: item.cfi
              })
            })
          }
          _this.markIdArray = i;
          easyMarker.highlightLines(i);
        },
        failRes => {
          this.$routerGo(this, "replace", {
            path: "/error/emptyPage",
            query: {
              from: "",
              info: "电子书已下架，请联系管理员！"
            }
          });
        }
      )
    },
    // 保存，删除书签
    saveHighLineNotes(opt, noteCfi, title, content, href) {
      utilJs.postMethod(`${global.apiurl}ebooks/saveHighLineNotes/${this.ebId}`, { opt: opt, noteCfi: noteCfi, title: title, content: content, href: href }, res => {
        this.markIdArray[this.markIdArray.length - 1].lineId = res;
        this.markingRestory();
        if (opt == 0) {
          this.$showCjToast({
            text: "删除划线成功",
            type: "success",
          });
          return true;
        }
      }, failRes => {
        this.$routerGo(this, "replace", {
          path: "/error/emptyPage",
          query: {
            from: "",
            info: "电子书已下架，请联系管理员！"
          }
        });
      })
    },
    initTextMark() {
      console.log('--------我执行了多少次-------')

      easyMarker && easyMarker.destroy();
      easyMarker = new EasyMarker({
        mask: {
          color: '#407ff2',
          opacity: 0.2
        },
        cursor: {
          color: '#407ff2'
        },
        menuStyle: {
          menu: {
            borderRadius: '8px',
            width: '97px',
            height: '60px'
          },
          item: {
            fontSize: '15px',
            padding: '8px 10px',
            lineHeight: '30px',
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
            alignItems: 'center'
          },
          triangle: {
            borderTop: '0.5rem solid #262626',
            borderRight: '0.5rem solid transparent',
            borderLeft: '0.5rem solid transparent',
          }
        },
        highlight: {
          color: 'rgba(241,151,37,.3)'
        },
        menuItems: [
          {
            text: '划线',
            type: 'select',
            id: '302',
          },
          {
            text: '删除划线',
            type: 'highlight',
            id: '301'
          }
        ],
        disableTapHighlight: !0
      });
      this.bindEasyMarker();

    },
    bindEasyMarker() {
      let _this = this;
      const currentLocation = this.book.rendition.currentLocation();//获取当前的位置
      if (!currentLocation) return;
      console.log("bindEasyMarker-currentLocation", currentLocation)
      const iframe = document.querySelector(`[ref="${currentLocation.end.index}"] iframe`);
      const container = iframe ? iframe.contentDocument.documentElement : null;
      if (!container) return;
      easyMarker.create(container, document.body, document.querySelectorAll(".article-body>:not(.text)"));
      easyMarker.onMenuClick(function (id, data, option) {
        if (id === '302') {
          var n = document.createRange();
          n.setStart(data.anchorNode, data.anchorOffset);
          n.setEnd(data.focusNode, data.focusOffset);
          var i = _this.book.rendition.getContents()[0].cfiFromRange(n);
          this.highlightLine(data, i);
          _this.markIdArray.push({
            id: _this.markIdArray.length,
            cfi: i
          })
          _this.saveHighLineNotes(1, i, _this.getSectionName(), data.toString(), currentLocation.start.href)
        } else {
          easyMarker.cancelHighlightLine(option.id)
          _this.saveHighLineNotes(0, option.id, '', '', '')
        }
      })
      easyMarker.onSelectStatusChange((val) => {
        this.selectStatus = val;
      })
      easyMarker.registerEventHook(_this.touchHook);
      // easyMarker.onHighlightLineClick(_this.highlightClickHandle)
      this.textMarkRestore(currentLocation.start.href);
    },
    handleClickHightLine(item) {
      easyMarker.cancelHighlightLine(item.cfi)
      this.saveHighLineNotes(0, item.cfi, '', '', '')
    },
    createdStyle() {
      var style = this.getStyle('resect');
      let currentLocation = this.rendition.currentLocation();//获取当前的位置
      let currentIframe = document.querySelector(`[ref="${currentLocation.end.index}"] iframe`)
      var head = currentIframe.contentDocument.documentElement.getElementsByTagName('head')[0];
      if (!document.getElementsByTagName('iframe')[0].contentDocument.getElementById('resect')) {
        head.appendChild(style);
      }
    },
    getStyle(id) {
      var style = document.createElement('style');
      style.type = 'text/css';
      style.rel = 'stylesheet';
      style.id = id;
      var styleText = 'body{margin:10px;font-size:1.0em;word-wrap:break-word;color:' + this.themeList[this.defaultTheme].style.body.color + '} .textMarkMenuIcon {width:19px;height:19px;} ul,li{list-style-type:none;margin:0;padding:0;} p{text-indent:2em; line-height:1.5em; margin-top:0; margin-bottom:1.5em;} .catalog{line-height: 3.5em;height: 3.5em;font-size: 0.8em;overflow: hidden;text-overflow: ellipsis;} li{border-bottom: 1px solid #D5D5D5;} h1{font-size:1.6em; font-weight:bold;} h1.kindle-cn-heading-1{font-size:1.6em;} h2{display: block;font-size: 1.2em;font-weight: bold;margin-bottom: 0.83em;margin-left: 0;margin-right: 0;margin-top: 1em;} h2.kindle-cn-heading2{font-size:1.2em;} .mbppagebreak{display: block;margin:0;} a{ color: inherit;text-decoration: none;cursor: default; pointer-events:none;overflow: hidden;text-overflow: ellipsis;} a[href]{color: blue;text-decoration: none;cursor: pointer; pointer-events:none;overflow: hidden;text-overflow: ellipsis;} .italic{font-style: italic;}';
      style.appendChild(document.createTextNode(styleText));
      return style;
    },
    refleshLocation() {
      this.selectStatus = 'none'
      this.initTextMark();
      // 划线功能注释下期解开
      this.createdStyle();
      // setTimeout(() => {
      const currentLocation = this.book.rendition.currentLocation();//获取当前的位置
      console.log("refleshLocation-currentLocation", currentLocation);
      if (currentLocation && currentLocation.start) {
        const startCfi = currentLocation.start.cfi;
        const progress = this.book.locations.percentageFromCfi(startCfi);//获取当前的百分比
        this.setProgress(Math.floor(progress * 100));//设置progress，等于设置了进度条进度
        this.setSection(currentLocation.start.index);//当前页码
        this.sectionName = this.getSectionName();
        if (this.bookmark && this.bookmark.length > 0) {
          if (this.bookmark.some(item => item.cfi === currentLocation.start.cfi)) {
            this.isBookMark = true;
          } else {
            this.isBookMark = false
          }
        } else {
          this.isBookMark = false
        }
        this.saveReadingRecord(0, page, currentLocation.start.cfi, 0, currentLocation.start.href, this.progress);
        // this.setProgressRatio(this.progress, 0);
        this.ifTextShow = false;
        this.$loading.hide();
        this.cloneIframe();
        // 将当前变化的数据传递给后台存储
        // localStorage.setItem("locations", startCfi);//存储当前进度条
      }
      // }, 1000);
    },
    // 上一页
    prePage() {
      if (this.ebookDetail.formatType == 1) {
        if (page > 1) {
          page--;
          this.getEbookContentByPage();
          // this.saveReadingRecord(0, page, '', 0, '', this.progress);
        } else {
          this.$cjConfirm({
            title: '', //
            titleCenter: true, //标题是否居中
            message: '当前已经是第一页',
            messageCenter: true, //内容是否居中
            showMasker: true, //是否显示透明背景
            clickCloseModal: false, //是否点击透明背景关闭弹窗
            showCancelButton: false, //是否显示取消按钮
            cancelButtonText: '', //取消按钮文本
            confirmButtonText: '', //确认按钮文本
          })
          return true;
        }
      } else {
        this.$loading.show();
        if (this.rendition) {
          let currentLocation = this.book.rendition.currentLocation();//获取当前的位置
          if (!currentLocation.start) {
            this.$loading.hide();
            return;
          }
          if (currentLocation.start.index >= 1) {
            if (this.pageTurnType == 2 || this.pageTurnType == 4) {
              if (!this._readElem) return;
              if (this._pageTurnAniming) {
                this.$loading.hide();
                return;
              };
              this._pageTurnAniming = true;
              this._direction = -1;
              let className = `type-${this.pageTurnType}_${this._direction == 1 ? 'l' : 'r'}`;
              this._readElem.classList.add('active-left');
              this.rendition.prev().then(() => {
                currentLocation = this.book.rendition.currentLocation();//获取当前的位置
                // this.refleshLocation();
                this.setSection(currentLocation.start.index);//当前页码
                if (this.pageTurnType == 2) {
                  // 平移的时候
                  this._readCloneElem.addEventListener("animationend", this.animationendCB);
                  this._readElem.addEventListener("animationend", this.animationendCB);
                  this._readElem.classList.add(className);
                  this._readCloneElem.classList.add(className);
                } else {
                  // 覆盖的时候
                  this._readElem.addEventListener("animationend", this.animationendCB);
                  this._readElem.classList.add(className);
                }
              })
            } else {
              if (this.pageTurnType == 3) {
                if (this._pageTurnAniming) return;
                this._pageTurnAniming = true;
                this._pageTurnTypeElem.classList.add("prev");
                setTimeout(() => {
                  this.rendition.prev().then(() => {
                    currentLocation = this.book.rendition.currentLocation();
                    this.refleshLocation();
                    this.setSection(currentLocation.start.index);//当前页码
                  });
                }, 350)
              } else {
                this.rendition.prev().then(() => {
                  currentLocation = this.book.rendition.currentLocation();
                  this.refleshLocation();
                  this.setSection(currentLocation.start.index);//当前页码
                });
              }
            }
            this.$loading.hide();
          } else {
            this.$cjConfirm({
              title: '', //
              titleCenter: true, //标题是否居中
              message: '当前已经是第一页',
              messageCenter: true, //内容是否居中
              showMasker: true, //是否显示透明背景
              clickCloseModal: false, //是否点击透明背景关闭弹窗
              showCancelButton: false, //是否显示取消按钮
              cancelButtonText: '', //取消按钮文本
              confirmButtonText: '', //确认按钮文本
            })
            this.$loading.hide();
            return true;
          }
        }
      }
    },
    // 下一页
    nextPage() {
      let _this = this;
      // 判断pdf时还是epub时
      if (this.ebookDetail.formatType == 1) {
        // 判断当前页数小于试读页数时不执行接口
        if (this.hasPermission == false && this.watchPermission == 1 && (page >= this.trailChaptersNum) && (page < this.totalPageNum)) {
          this.$loading.hide();
          this.$cjConfirm({
            title: '', //
            titleCenter: true, //标题是否居中
            message: '试读结束啦！意犹未尽？立即购买此书，继续阅读~',
            messageCenter: true, //内容是否居中
            showMasker: true, //是否显示透明背景
            clickCloseModal: false, //是否点击透明背景关闭弹窗
            showCancelButton: true, //是否显示取消按钮
            cancelButtonText: '', //取消按钮文本
            confirmButtonText: '', //确认按钮文本
            onConfirm() {
              _this.clickBuy();
            }, //确认事件回调
            onCancel() {
            }, //取消事件回调
          })
          return true;
        }
        if (page == this.totalPageNum) {
          this.$cjConfirm({
            title: '', //
            titleCenter: true, //标题是否居中
            message: '已经到最后一页了',
            messageCenter: true, //内容是否居中
            showMasker: true, //是否显示透明背景
            clickCloseModal: false, //是否点击透明背景关闭弹窗
            showCancelButton: false, //是否显示取消按钮
            cancelButtonText: '', //取消按钮文本
            confirmButtonText: '', //确认按钮文本
          })
          this.$loading.hide();
          return true;
        } else {
          page++;
          this.getEbookContentByPage();
          // this.saveReadingRecord(0, page, '', 0, '', this.progress);
          this.$loading.hide();
        }
        // 判断当前pdfIndex >= pdfArray得长度得时候再次请求数据
        // if (this.pdfIndex >= this.pdfArray.length) {
        //   this.getEbookContentByPage();
        // }
      } else {
        this.$loading.show();
        if (this.rendition) {
          let currentLocation = this.book.rendition.currentLocation();//获取当前的位置
          if (this.hasPermission == false && this.watchPermission == 1 && ((currentLocation.end.index - 1 == this.trailChaptersNum && currentLocation.end.displayed.page == currentLocation.end.displayed.total) || currentLocation.end.index - 1 > this.trailChaptersNum) && (currentLocation.end.index < this.totalPageNum)) {
            this.$cjConfirm({
              title: '', //
              titleCenter: true, //标题是否居中
              message: '试读结束啦！意犹未尽？立即购买此书，继续阅读~',
              messageCenter: true, //内容是否居中
              showMasker: true, //是否显示透明背景
              clickCloseModal: false, //是否点击透明背景关闭弹窗
              showCancelButton: true, //是否显示取消按钮
              cancelButtonText: '', //取消按钮文本
              confirmButtonText: '', //确认按钮文本
              onConfirm() {
                _this.clickBuy();
              }, //确认事件回调
              onCancel() {
              }, //取消事件回调
            })
            this.$loading.hide();
            return true;
          } else {
            if (currentLocation.start.percentage == 1 && (currentLocation.start.displayed.page == currentLocation.start.displayed.total)) {
              this.$cjConfirm({
                title: '', //
                titleCenter: true, //标题是否居中
                message: '已经到最后一页了',
                messageCenter: true, //内容是否居中
                showMasker: true, //是否显示透明背景
                clickCloseModal: false, //是否点击透明背景关闭弹窗
                showCancelButton: false, //是否显示取消按钮
                cancelButtonText: '', //取消按钮文本
                confirmButtonText: '', //确认按钮文本
              })
              this.$loading.hide();
              return true;
            } else {
              if (this.pageTurnType == 2 || this.pageTurnType == 4) {
                if (!this._readElem) return;
                if (this._pageTurnAniming) {
                  this.$loading.hide();
                  return;
                };
                this._pageTurnAniming = true;
                this._direction = 1;
                let className = `type-${this.pageTurnType}_${this._direction == 1 ? 'l' : 'r'}`;
                if (this.pageTurnType == 2) {
                  this._readElem.classList.add('active-right');
                } else {
                  this._readCloneElem.classList.add('active-up');
                }
                this.rendition.next().then(() => {
                  // this.refleshLocation();
                  this.setSection(currentLocation.start.index);//当前页码
                  if (this.pageTurnType == 2) {
                    this._readCloneElem.addEventListener("animationend", this.animationendCB);
                    this._readElem.addEventListener("animationend", this.animationendCB);
                    this._readElem.classList.add(className);
                    this._readCloneElem.classList.add(className);
                  } else {
                    this._readCloneElem.addEventListener("animationend", this.animationendCB);
                    this._readCloneElem.classList.add(className);
                  }
                });
                this.$loading.hide();
              } else {
                this.$loading.hide();
                if (this.pageTurnType == 3) {
                  if (this._pageTurnAniming) return;
                  this._pageTurnAniming = true;
                  this._pageTurnTypeElem.classList.add("next");
                }
                this.rendition.next().then(() => {
                  currentLocation = this.book.rendition.currentLocation();
                  console.log("this.rendition", this.rendition)
                  // this.refleshLocation();
                  if (!currentLocation.start) {
                    return;
                  }
                  this.setSection(currentLocation.end.index);//当前页码
                });
              }
            }
          }
        }
      }
    },
    // 上一章
    prevSection() {
      if (this.ebookDetail.formatType == 1) {
        if (page > 1) {
          page--;
          this.getEbookContentByPage();
          // this.saveReadingRecord(0, page, '', 0, '');
        } else {
          this.$cjConfirm({
            title: '', //
            titleCenter: true, //标题是否居中
            message: '当前已经是第一页',
            messageCenter: true, //内容是否居中
            showMasker: true, //是否显示透明背景
            clickCloseModal: false, //是否点击透明背景关闭弹窗
            showCancelButton: false, //是否显示取消按钮
            cancelButtonText: '', //取消按钮文本
            confirmButtonText: '', //确认按钮文本
          })
          return true;
        }
      } else {
        this.$loading.show();
        if (this.bookAvailable) {
          this.$loading.hide();
          this.$showCjToast({
            text: "章节加载中,请稍后",
            type: "warn",
          });
          return true;
        }
        if (this.section > 0 && !this.bookAvailable) {
          this.setSection(this.section - 1);
          this.displaySection();
          this.$loading.hide();
        } else {
          this.$cjConfirm({
            title: '', //
            titleCenter: true, //标题是否居中
            message: '当前已经是第一章',
            messageCenter: true, //内容是否居中
            showMasker: true, //是否显示透明背景
            clickCloseModal: false, //是否点击透明背景关闭弹窗
            showCancelButton: false, //是否显示取消按钮
            cancelButtonText: '', //取消按钮文本
            confirmButtonText: '', //确认按钮文本
          })
          this.$loading.hide();
          return true;
        }
      }
    },
    // 购买电子书
    clickBuy() {
      if (this.bindPhoneSetting && this.bindPhoneSetting.buyBind) {
        if (utilJs.goBindMobile()) return;
      }
      // 关联售卖的课程在试看流程中点击购买跳回本页面，弹窗显示关联售卖
      if (this.ebookDetail && this.ebookDetail.isSaleOnly == 0) {
        this.$routerGo(this, "push", {
          path: `/homePage/ebooks/ebooksDetail?id=${this.ebId}`
        })
        sessionStorage.setItem('showEbooksIsSaleOnly', this.ebookDetail.isSaleOnly)
        return;
      }
      let queryT = null;
      queryT = {
        cId: 0,
        extId: this.ebId,
        ckFrom: global.ckFrom.ebooks,
        extraId: 0,
      }
      this.$routerGo(this, "push", {
        path: "/homePage/course/coursePay",
        query: queryT
      });
    },
    // 下一章
    nextSection() {
      let _this = this;
      if (this.ebookDetail.formatType == 1) {
        // 判断当前页数小于试读页数时不执行接口
        if (this.hasPermission == false && this.watchPermission == 1 && (page >= this.trailChaptersNum) && (page < this.totalPageNum)) {
          this.$cjConfirm({
            title: '', //
            titleCenter: true, //标题是否居中
            message: '试读结束啦！意犹未尽？立即购买此书，继续阅读~',
            messageCenter: true, //内容是否居中
            showMasker: true, //是否显示透明背景
            clickCloseModal: false, //是否点击透明背景关闭弹窗
            showCancelButton: true, //是否显示取消按钮
            cancelButtonText: '', //取消按钮文本
            confirmButtonText: '', //确认按钮文本
            onConfirm() {
              _this.clickBuy();
            }, //确认事件回调
            onCancel() {
            }, //取消事件回调
          })
          return true;
        }
        if (page == this.totalPageNum) {
          this.$cjConfirm({
            title: '', //
            titleCenter: true, //标题是否居中
            message: '已经到最后一页了',
            messageCenter: true, //内容是否居中
            showMasker: true, //是否显示透明背景
            clickCloseModal: false, //是否点击透明背景关闭弹窗
            showCancelButton: false, //是否显示取消按钮
            cancelButtonText: '', //取消按钮文本
            confirmButtonText: '', //确认按钮文本
          })
          return true;
        } else {
          page++;
          this.getEbookContentByPage();
          // this.saveReadingRecord(0, page, '', 0, '', this.progress);
        }
      } else {
        this.$loading.show();
        const currentLocation = this.book.rendition.currentLocation();//获取当前的位置
        if (currentLocation.start && currentLocation.start.index <= this.book.spine.length - 1 && !this.bookAvailable) {
          this.setSection(currentLocation.start.index + 1);
          if (this.hasPermission == false && this.watchPermission == 1 && (currentLocation.start.index > this.trailChaptersNum) && (currentLocation.start.index < this.totalPageNum)) {
            this.$cjConfirm({
              title: '', //
              titleCenter: true, //标题是否居中
              message: '试读结束啦！意犹未尽？立即购买此书，继续阅读~',
              messageCenter: true, //内容是否居中
              showMasker: true, //是否显示透明背景
              clickCloseModal: false, //是否点击透明背景关闭弹窗
              showCancelButton: true, //是否显示取消按钮
              cancelButtonText: '', //取消按钮文本
              confirmButtonText: '', //确认按钮文本
              onConfirm() {
                _this.clickBuy();
              }, //确认事件回调
              onCancel() {
              }, //取消事件回调
            })
            this.$loading.hide();
            return true;
          } else {
            if (currentLocation.start.index >= (this.book.spine.length - 1)) {
              this.$cjConfirm({
                title: '', //
                titleCenter: true, //标题是否居中
                message: '已经到最后一章了',
                messageCenter: true, //内容是否居中
                showMasker: true, //是否显示透明背景
                clickCloseModal: false, //是否点击透明背景关闭弹窗
                showCancelButton: false, //是否显示取消按钮
                cancelButtonText: '', //取消按钮文本
                confirmButtonText: '', //确认按钮文本
              })
              this.$loading.hide();
              return true;
            } else {
              this.displaySection();
              this.$loading.hide();
            }
          }
        } else {
          this.$loading.hide();
          this.$showCjToast({
            text: "章节加载中,请稍后",
            type: "warn",
          });
          return true
        }
      }
    },
    // 展示上一章下一章的方法封装
    displaySection() {
      const sectionInfo = this.book.section(this.section); //获得对应章节对象
      if (sectionInfo && sectionInfo.href) {
        this.book.rendition.display(sectionInfo.href).then(() => {
          this.refleshLocation();
        });
      }
    },
    // 点击跳转评论
    handleClickComment() {
      this.$routerGo(this, "push", {
        path: "/homePage/ebooks/ebooksComment",
        query: {
          ebId: this.ebId
        }
      })
    },
    // 点击阅读设置
    handleClickReadSet() {
      this.isShowReadSet = true;
    },
    // 点击目录展开
    handleClickShowContent() {
      this.ifShowContent = true;
      this.isShowReadSet = false;
      // this.ifThemeShow = false;
      // this.ifFontSizeShow = false;
    },
    hideContent() {
      this.ifShowContent = false;
      this.$refs.ebooksContent.isEdit = false;
    },
    // 点击删除书签
    handleClickBookMark(item, index) {
      let _this = this;
      this.$cjConfirm({
        title: '', //
        titleCenter: true, //标题是否居中
        message: '确定要删除此书签？',
        messageCenter: true, //内容是否居中
        showMasker: true, //是否显示透明背景
        clickCloseModal: false, //是否点击透明背景关闭弹窗
        showCancelButton: true, //是否显示取消按钮
        cancelButtonText: '', //取消按钮文本
        confirmButtonText: '', //确认按钮文本
        onConfirm() {
          _this.removeBookmark(item, index);
        }, //确认事件回调
        onCancel() {
        }, //取消事件回调
      })
    },
    // 删除书签
    handleClickDelete(isArrayPdfMark) {
      this.pdfmark.forEach(i => {
        if (i.isChecked == true) {
          isArrayPdfMark.push(i.page)
        }
      })
      if (isArrayPdfMark.length == 0) {
        this.$showCjToast({
          text: "未选中书签",
          type: "warn",
        });
        return;
      }
      let isInsertPdf = this.pdfmark.some(item => {
        if (isArrayPdfMark.includes(item.page)) {
          return true;
        }
      })
      if (isInsertPdf) {
        this.pdfmark = this.pdfmark.filter(item => {
          return !isArrayPdfMark.includes(item.page)
        })
        this.optBookmark(0, isArrayPdfMark, '', '', '')
        this.$showCjToast({
          text: "成功删除书签",
          type: "success",
        });
        this.getEbookContentByPage();
      } else {
        this.$showCjToast({
          text: "未选中书签",
          type: "warn",
        });
        return;
      }
      // if (isArrayPdfMark.length > 0) {
      //   this.pdfmark = this.pdfmark.filter(item => {
      //     return !isArrayPdfMark.includes(item.page)
      //   })
      //   this.optBookmark(0, isArrayPdfMark, '', '')
      //   this.$showCjToast({
      //     text: "成功删除书签",
      //     type: "success",
      //     isShowMask: "true"
      //   });
      // }
    },
    removeBookmark(item, index) {
      let bookMarkString = {
        cfi: item.cfi,
        text: item.text,
        title: item.title,
        time: item.time,
        ebbkId: item.ebbkId
      }
      if (this.bookmark.length > 0) {
        this.bookmark.splice(index, 1)
        // 删除数据
        this.optBookmark(0, '', bookMarkString, item.ebbkId, '')
        this.isBookMark = false;
        this.$showCjToast({
          text: "成功删除书签",
          type: "success",
        });
      }
    },
    moveBookmark() {
      if (this.formatType == 2) {
        const currentLocation = this.book.rendition.currentLocation()
        const cfi = currentLocation.start.cfi
        if (this.bookmark) {
          let bookMarkString = this.bookmark.filter(item => item.cfi == cfi)[0];
          if (bookMarkString) {
            this.optBookmark(0, '', bookMarkString, bookMarkString.ebbkId, '')
            this.bookmark = this.bookmark.filter(item => item.cfi !== cfi);
            this.isBookMark = false;
            this.$showCjToast({
              text: "成功删除书签",
              type: "success",
            });
          }
        }
      } else {
        this.pdfmark = this.pdfmark.filter(item => item.page !== page);
        this.isBookMark = false;
        this.optBookmark(0, page, '', '', '')
        this.$showCjToast({
          text: "成功删除书签",
          type: "success",
        });
      }
    },
    // 点击添加书签
    handleClickAddBook(isBookMark) {
      if (this.ebookDetail.formatType == 1) {
        if (isBookMark) {
          // 对当前点击当页得数据进行重组
          if (this.pdfmark.length == 0) {
            this.pdfmark = this.defaultPdfArray;
            this.optBookmark(1, page, '', '', '');
            this.$showCjToast({
              text: "成功添加书签",
              type: "success",
            })
            this.isBookMark = true;
          } else if (this.pdfmark.length > 0) {
            // 当数组长度大于0得时候，判断当前添加得书签是否已经存在,
            // 如果this.pdfmark数组对象中包含pdfPageFlg，就返回true，否则就false
            let pdfPageFlg = this.defaultPdfArray[0].page;
            let isInsertPdf = this.pdfmark.some(item => {
              if (item.page == pdfPageFlg) {
                return true;
              }
            })
            if (isInsertPdf) {
              this.$cjConfirm({
                title: '', //
                titleCenter: true, //标题是否居中
                message: '已存在当前书签,无需添加',
                messageCenter: true, //内容是否居中
                showMasker: true, //是否显示透明背景
                clickCloseModal: false, //是否点击透明背景关闭弹窗
                showCancelButton: false, //是否显示取消按钮
                cancelButtonText: '', //取消按钮文本
                confirmButtonText: '', //确认按钮文本
              })
              this.isBookMark = false;
            } else {
              this.pdfmark = [...this.pdfmark, ...this.defaultPdfArray];
              this.optBookmark(1, page, '', '', '')
              this.$showCjToast({
                text: "成功添加书签",
                type: "success",
              });
              this.isBookMark = true;
            }
          }
        } else {
          this.moveBookmark();
        }
      } else {
        if (isBookMark) {
          if (!this.bookmark) {
            this.bookmark = [];
          }
          const currentLocation = this.book.rendition.currentLocation();
          const cfibase = currentLocation.start.cfi.replace(/!.*/, '');
          const cfistart = currentLocation.start.cfi.replace(/.*!/, '').replace(/\)$/, '');
          const cfiend = currentLocation.end.cfi.replace(/.*!/, '').replace(/\)$/, '');
          const cfirange = `${cfibase}!,${cfistart},${cfiend})`;
          this.book.getRange(cfirange).then(range => {
            const title = range.startContainer.textContent;
            const text = range.toString().replace(/\s\s/g, '');
            const myDate = new Date();
            // this.bookmark.push({
            //   cfi: currentLocation.start.cfi,
            //   text: text,
            //   title: title,
            //   time: this.dateStr(myDate)
            // })
            let bookMarkString = {
              cfi: currentLocation.start.cfi,
              text: text,
              title: title,
              time: this.dateStr(myDate)
            }
            this.optBookmark(1, page, bookMarkString, '', currentLocation.start.href)

            // localStorage.setItem("bookmark", bookMarkString);//存储当前书签
          })
        } else {
          this.moveBookmark();
        }
      }
    },
    // 点击主题
    handleClickTheme() {
      this.isShowReadSet = false;
      // this.ifMenuShow = false;
      // this.ifThemeShow = !this.ifThemeShow;
      // if (this.ifFontSizeShow) {
      //   this.ifFontSizeShow = false;
      // }
    },
    // 设置主题色
    setTheme(index) {
      this.themes.select(this.themeList[index].name);
      this.themeBackground = this.themeList[index].style.body.background;
      this.pageTurnBackground = this.themeList[index].style.pageTurn.background;
      this.defaultTheme = index;
      localStorage.setItem('defaultTheme', this.defaultTheme);
      this.cloneIframe();
    },
    registerTheme() {
      this.themeList.forEach(theme => {
        this.themes.register(theme.name, theme.style)
      })
    },
    // 点击字体
    handleClickSize() {
      // this.ifMenuShow = false;
      // this.ifFontSizeShow = !this.ifFontSizeShow;
      // if (this.ifThemeShow) {
      //   this.ifThemeShow = false;
      // }
      this.isShowReadSet = false;
      this.$nextTick(() => {
        // this.$refs.ebooksFontSize.init();
      })
    },
    // 设置翻页模式
    setPageTurnType(type) {
      this.pageTurnType = type;
      localStorage.setItem('ebook_page_turn_type', type);
    },
    // 设置字体
    setFontSize(fontSize, Boolean) {
      this.defaultFontSize = fontSize
      if (this.themes) {
        this.themes.fontSize(fontSize + 'px');
      }
      localStorage.setItem('defaultFontSize', this.defaultFontSize);
      if (Boolean) {
        this.refleshLocation();
      }
    },
    dateStr(date) {
      //获取js 时间戳
      let time = new Date().getTime();
      //去掉 js 时间戳后三位，与php 时间戳保持一致
      time = parseInt((time - date) / 1000);
      //存储转换值
      let s;
      if (time < 60 * 10) {
        // 10分钟
        return '刚刚';
      } else if ((time < 60 * 60) && (time >= 60 * 10)) {
        // 超过10分钟少于一小时
        s = Math.floor(time / 60);
        return s + "分钟前";
      } else if ((time < 60 * 60 * 24) && (time >= 60 * 60)) {
        //超过1小时少于24小时
        s = Math.floor(time / 60 / 60);
        return s + "小时前";
      } else if ((time < 60 * 60 * 24 * 30) && (time >= 60 * 60 * 24)) {
        //超过1天少于30天内
        s = Math.floor(time / 60 / 60 / 24);
        return s + "天前";
      } else {
        //超过30天ddd
        let dateTime = new Date(parseInt(date));
        return dateTime.getFullYear() + "/" + (dateTime.getMonth() + 1) + "/" + dateTime.getDate();
      }
    },
    // 渲染电子书对象
    // refreshLocation() {
    //   const currentLocation = this.book.rendition.currentLocation();
    //   if (currentLocation && currentLocation.start) {
    //     const startCfi = currentLocation.start.cfi;
    //     const progress = this.book.locations.percentageFromCfi(startCfi);
    //     this.setProgress(Math.floor(progress * 100));//进度
    //     this.setSection(currentLocation.start.index);//当前页码
    //     localStorage.setItem("locations", startCfi);//存储当前进度条
    //   }
    // },
    display(target, cb) {
      if (target) {
        this.book.rendition.display(target).then(() => {
          this.refleshLocation()
          if (cb) cb()
        })
      } else {
        this.book.rendition.display().then(() => {
          this.refleshLocation()
          if (cb) cb()
        })
      }
    },
    setProgress(progress) {
      this.progress = progress;
    },
    setSection(section) {
      this.section = section;
    },
    // 获取章节名称
    getSectionName() {
      if (this.section) {
        if (this.book) {
          const sectionInfo = this.book.section(this.section);
          if (sectionInfo && sectionInfo.href) {
            if (this.book.navigation && this.book.navigation.get(sectionInfo.href)) {
              return this.book.navigation.get(sectionInfo.href).label;
            }
          }
        }
      }
      return '';
    },
    flatten(array) {
      return [].concat(...array.map(item => [].concat(item, ...this.flatten(item.subitems))));
    },
    // 电子书得解析和渲染
    initRendition() {
      let bookConfig = {
        width: innerWidth,
        height: innerHeight,
        method: "default"
      }
      this.rendition = this.book.renderTo('read', bookConfig)
      this.rendition.display();
      this.rendition.on("relocated", (location) => {
        console.log(this.rendition)
        console.log("locationChanged", location);
        console.log("locationChanged start", location.start.cfi);
        console.log("locationChanged end", location.end.cfi);
        localStorage.setItem("epubcfi", location.start.cfi);
        this.cloneIframe();
      });
      this.rendition.on("rendered", () => {
        this.refleshLocation();
      })
      console.log("this.rendition", this.book, this.rendition)
      // 获取Theme对象
      this.themes = this.rendition.themes;
      this.registerTheme();
      this.setTheme(this.defaultTheme);
      this.book.rendition.display().then(() => {
        this._readElem = document.getElementById("read");
        this._readCloneElem = document.getElementById("J_read-clone")
        const location = this.readingRecord && this.readingRecord.cfi;
        if (this.eBooksSrc != '') {
          this.display(this.eBooksSrc, () => {
            this.refleshLocation();
          })
        } else {
          if (location) {
            // 渲染存储得值
            this.book.rendition.display(location).then(() => {
              this.refleshLocation();
              this.setFontSize(this.defaultFontSize, false)
            })
            // setTimeout(() => {
            //   this.book.rendition.display(location).then(() => {
            //     this.refleshLocation();
            //   })
            // }, 1000)
          } else {
            this.display();
          }
        }
      })
      this.initTurnElemEvent();
      // this.book.rendition.on('touchstart', event => {
      //   event.preventDefault();
      //   this.touchSlide.startX = event.targetTouches[0].pageX;
      //   this.touchSlide.startY = event.targetTouches[0].pageY;
      //   console.log('----touchstart-----', this.touchSlide)
      // })
      // this.book.rendition.on('touchmove', event => {
      //   event.stopPropagation();
      //   this.touchSlide.endX = event.targetTouches[0].pageX;
      //   this.touchSlide.endY = event.targetTouches[0].pageY;
      //   console.log('----touchmove-----', this.touchSlide)
      // })
    },
    showEpub() {
      let _this = this;
      // 电子书实例
      this.$loading.show();
      this.book = ePub(DOWNLLOAD_URL);
      if (!this.book.archived && !this.book.isOpen) {
        this.$loading.hide();
        this.$showCjToast({
          text: "该电子书解析失败，请联系管理员",
          type: "warn",
        }).then(() => {
          _this.$routerGo(_this, "replace", {
              path: `/homePage/ebooks/ebooksDetail?id=${_this.ebId}`
            })
        });
        return;
      }
      _this.initRendition();
      // 获取Location对象this.book.location
      // 通过epubjs的钩子函数来实现
      // 通过navigation对象获取目录
      this.book.ready.then(() => {
        return this.book.locations.generate()
      }).then(result => {
        _this.bookAvailable = false;
        _this.locations = _this.book.locations;
        _this.refleshLocation();
      })
    },
    initTurnElemEvent() {
      this._pageTurnTypeElem = document.getElementById("J_page-turn-anim3");
      console.log("_pageTurnTypeElem", this._pageTurnTypeElem)
      this._pageTurnTypeElem.addEventListener("animationend", () => {
        this._pageTurnTypeElem.classList.remove("prev", "next");
        this._pageTurnAniming = false;
      });
    },
    animationendCB(event) {
      let target = event.target;
      let className = `type-${this.pageTurnType}_${this._direction == 1 ? 'l' : 'r'}`;
      target.classList.remove(className);
      target.classList.remove('active-left');
      target.classList.remove('active-right');
      target.classList.remove('active-up');
      target.removeEventListener("animationend", this.animationendCB);
      this._pageTurnAniming = false;
    }
  },
  mounted() {
    // this.showEpub();
    this.isWechatIos = navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    //如果是ios,则去掉minHeight设置，防止底部前进后退导航挡住页面
    if (this.isWechatIos && this.formatType == 2) {
      document.getElementById('ebooks').style.minHeight = '';
    }
    // 禁止右键
    document.oncontextmenu = function () {
      return false;
    }
    // 初始化设置字体
    // if (this.formatType == 2) {
    //   this.$nextTick(() => {
    //     // this.$refs.ebooksFontSize.init();
    //   })
    // }
  },
  activated() {
    // 判断是否阅读过显示引导页
    if (localStorage.getItem("readGuidePage")) {
      this.readGuidePage = 0;
    } else {
      this.readGuidePage = 1;
      localStorage.setItem("readGuidePage", 0)
    }
    this.themeBackground = localStorage.getItem('defaultTheme') && this.themeList[localStorage.getItem('defaultTheme')].style.body.background || '#F2F2F2';
    this.pageTurnBackground = localStorage.getItem('defaultTheme') && this.themeList[localStorage.getItem('defaultTheme')].style.pageTurn.background || '#F2F2F2';
    page = this.$route.query.page || 0;
    pageIndex = 1;
    contentIndex = 1;
    this.isShowComment = false;
    this.accessToken = this.$route.query.accessToken || '';
    this.defaultTheme = localStorage.getItem('defaultTheme') || 0;
    this.defaultFontSize = localStorage.getItem('defaultFontSize') || 16;
    this.pageTurnType = localStorage.getItem('ebook_page_turn_type') != "undefined" && localStorage.getItem('ebook_page_turn_type') || 1; // 电子书翻页模式
    this.ttId = this.$route.query.ttId || '';
    this.tpId = this.$route.query.tpId || '';
    this.tlId = this.$route.query.tlId || '';
    // this.count = 0;
    this.canscroll = true;
    this.ifMenuShow = false;
    this.ifTextShow = false;
    // this.ifThemeShow = false;
    // this.ifFontSizeShow = false;
    this.isShowReadSet = false;
    this.isTouchFlage = false;
    this.beginX = '';
    this.beginY = '';
    this.endX = '';
    this.endY = '';
    this.swipeLeft = false;
    this.swipeRight = false;
    this.progress = 0;
    this.ifShowContent = false;
    this.bookAvailable = true;
    this.hasPermission = false;
    this.isTouchMove = false;
    this.navigation = {};
    this.ebookDetail = null;
    this.readingRecord = null;
    this.baseInfo = null;
    this.content = null;
    this.pdfIndex = 0;
    this.pdfUrl = '';
    this.totalPageNum = 0;
    this.dataStatus = 'HAS_MORE_DATA';
    this.ebId = this.$route.query.ebId;
    this.ebrId = this.$route.query.ebrId;
    this.inputPwd = this.$route.query.inputPwd;
    this.section = 1;
    this.pdfcatalog = [];
    this.pdfArray = [];
    this.bookmark = [];
    this.defaultPdfArray = [];
    this.pdfmark = [];
    this.sectionName = '';
    this.readMark = false;
    this.epiId = '';
    this.readLeft = false;
    this.readCenter = false;
    this.readRight = true;
    this.pdfTo = 0;
    this.touchSlide = {
      startX: 0,
      startY: 0,
      endX: 0,
      endY: 0,
      direction: -1
    };
    this.markIdArray = [];
    this.markingArray = [];
    this.bookmark = JSON.parse(localStorage.getItem("bookmark"));
    this.showEbookWatermark = localStorage.getItem('enableEbookWatermark') && localStorage.getItem('enableEbookWatermark') == '1' ? true : false;
    this._readElem = null;
    this._readCloneElem = null;
    this._direction = 1;
    this._clientWidth = window.innerWidth;
    this._animTime = 0.5;
    if (page > 0) {
      this.saveReadingRecord(0, page, '', 1, '', this.progress);
      // this.setProgressRatio(this.progress, 1);
    }

    import(/* webpackChunkName: "easyMarker" */"@/utils/easy-marker.esm").then(res => {
      EasyMarker = res.default;
    })
    import(/* webpackChunkName: "epub" */"@/utils/epub.min.js").then(res => {
      ePub = res.default;
      this.getEbookViwer();
    })
    getBindPhoneSetting(global.ckFrom.ebooks).then(res => {
      this.bindPhoneSetting = res;
    });
    // this.getEbookContentByPage();
    this.getIndexByPage();
  },
}
</script>

<style scoped>
.closeBig >>> p > img,
.closeBig >>> section > img,
.closeBig >>> div > img,
.closeBig >>> img {
  pointer-events: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -webkit-user-select: none;
  -o-user-select: none;
  user-select: none;
}
</style>
<style lang='scss' scoped>
$animTime:0.5s;
body,
html {
  overflow: hidden;
}
.ebooks {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  .ebook-reader-mask {
    position: absolute;
    z-index: 150;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
  .read-wrapper {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    // max-width: 16rem;
    margin: 0 auto;
    // margin-left: -8rem;
    height: 100%;
    z-index: 101;
    background-color: #efeff4;
    padding-top: 2.2rem;
    transition: transform 0.15s ease-out, -webkit-transform 0.15s ease-out;
    box-sizing: content-box;
    overflow: hidden;
    .pdfImg {
      object-fit: contain;
      width: 100%;
      height: 100%;
    }
    .read-book-container{
      width: 100%;
      height: 100%;
      position: relative;
    }
    .read-clone{
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: hidden;
      // 平移（向左滑动），下一页
      &.type-2_l{
        animation: slideOutLeft $animTime ease-out;
      }
      &.type-2_r{
        animation: slideOutRight $animTime ease-out;
      }
      &.type-4_l{
        animation: slideOutLeft $animTime ease-out;
      }
      &.active-up{
        z-index: 10;
      }

    }
    .read {
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom:0;
      &.active-left{
        transform: translate(-100%, 0);
      }
      &.active-right{
        transform: translate(100%, 0);
      }
      &.active-up{
        z-index: 10;
      }
      &.type-2_l{
        animation: slideInRight $animTime ease-out;
      }
      &.type-2_r{
        animation: slideInLeft $animTime ease-out;
      }
      // 覆盖（向左滑动），下一页
      // &.type-4_l{
      //   animation: slideOutLeft $anim-time ease-out;
      // }

      // 覆盖（向左滑动），上一页
      &.type-4_r{
        animation: slideInLeft $animTime ease-out;
      }
    }
    .read-mask {
      display: flex;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 100;
      width: 100%;
      height: 100%;
      // display: none;
      .read-left {
        flex: 0 0 5rem;
      }
      .read-center {
        flex: 1;
      }
      .read-right {
        flex: 0 0 5rem;
      }
    }
    .read-guidePage {
      display: flex;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 105;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.75);
      .read-guidePage-con {
        color: #fff;
        font-size: 0.55rem;
        img {
          margin: 0 auto 0.5rem auto;
        }
      }
      .read-guidePage-left {
        position: absolute;
        top: 0;
        left: 0;
        width: 35%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        flex: 0 0 35%;
        background: rgba(0, 0, 0, 0.85);
      }
      .read-guidePage-center {
        position: absolute;
        top: 0;
        left: 35%;
        width: 30%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        flex: 1;
        background: rgba(0, 0, 0, 0.85);
        .read-guidePage-con {
          text-align: center;
        }
      }
      .read-guidePage-right {
        position: absolute;
        top: 0;
        right: 0;
        width: 35%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        flex: 0 0 35%;
        background: rgba(0, 0, 0, 0.85);
        .read-guidePage-con {
          text-align: right;
        }
      }
    }
    .read-guidePage-mark {
      display: flex;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 105;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.75);
      .read-guidePage-markCon {
        display: flex;
        justify-items: center;
        align-items: flex-end;
        flex-direction: column;
        width: 100%;
        img {
          width: 5rem;
          height: 4.5rem;
        }
        p {
          color: #fff;
          font-size: 0.4rem;
          margin-right: 1.8rem;
        }
      }
    }
  }
  .content-mask {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 103;
    display: flex;
    width: 100%;
    height: 100%;
    background-color: rgba(51, 51, 51, 0.8);
  }
}
.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s linear;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
.fade-enter-to,
.fade-leave {
  opacity: 1;
}
.ebook-bookmark-icon-wrapper {
  position: fixed;
  right: 0;
  top: 0;
  margin-right: 0.26667rem;
  z-index: 103;
  .bookmark {
    width: 0;
    height: 0;
    border-width: 0.75rem 0.25rem 0.25rem 0.25rem;
    border-color: white white transparent white;
  }
}
.pdfBook {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  align-items: center;
  background-color: #171c19;
  .pdfBook-content {
    height: 100%;
    width: 100vw;
    margin: 0 auto;
    .pinch-zoom-container {
      width: 100%;
      height: 100%;
    }
  }
}
// .page-turn-anim3{
//   position: fixed;
//   left:0;
//   top: 0;
//   left: 0;
//   width: 100%;;
//   bottom: 0;
//   z-index: 0;
//   -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.27),
//           0 0 60px rgba(0, 0, 0, 0.06) inset;
//   -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.27),
//     0 0 40px rgba(0, 0, 0, 0.06) inset;
//   box-shadow: 0 1px 4px rgba(0, 0, 0, 0.27),
//     0 0 40px rgba(0, 0, 0, 0.06) inset;
//   transform: translate(-300%, 0);
//   &.next{
//     z-index: 101;
//     animation:slideOutLeft 1s ease;
//   }
//   &.prev{
//     z-index: 101;
//     animation:slideInLeft 1s ease-out;
//   }
// }
// @keyframes slideOutLeft {
//   0% {
//     -webkit-transform: translate3d(0,0,0);
//     transform: translate3d(0,0,0);
//     opacity: 1;
//   }
//   30% {
//     opacity: 1;
//   }
//   to {
//     -webkit-transform: translate3d(-100%, 0, 0);
//     transform: translate3d(-100%, 0, 0);
//     opacity: 0;
//   }
// }

.epub-view-clone{
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  white-space: nowrap;
  display: flex;
  flex-direction: row;
}


@keyframes slideInLeft {
  0% {
    -webkit-transform: translate3d(-100%, 0, 0);
    transform: translate3d(-100%, 0, 0);

  }
  to {
    -webkit-transform: translateZ(0);
    transform: translateZ(0);
  }
}


@keyframes slideInRight {
  0% {
    -webkit-transform: translate3d(100%,0,0);
    transform: translate3d(100%,0,0);
  }
  to {
    -webkit-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
  }
}

@keyframes slideOutLeft {
  0% {
    -webkit-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
  }
  to {
    -webkit-transform: translate3d(-100%,0,0);
    transform: translate3d(-100%,0,0);
  }
}

@keyframes slideOutRight {
  0% {
    -webkit-transform: translate3d(0,0,0);
    transform: translate3d(0,0,0);
  }
  to {
    -webkit-transform: translate3d(100%, 0, 0);
    transform: translate3d(100%, 0, 0);
  }
}


</style>